#-*- coding:utf-8 -*-
import os
import codecs
import traceback
import xml.dom.minidom as minidom

def covert_to_unicode(msg):
    '''将转入的编码转换为unicode，只接受utf-8和unicode编码'''
    errinfo = "error"
    __re_str = None
##    if isinstance(msg, unicode):
##        __re_str = msg
    if isinstance(msg, str):
    
        __re_str = msg.decode('utf-8')
      
    else:
        raise (Exception, '%s 必须为str或unicode类型' % msg)
    return __re_str
    
class CreateCovXml():
    errinfo = "error"
    def __init__(self, cov_xml_path):
        self.__cov_path = cov_xml_path
        self.__dom = None
        self.__root = None
    
    def _covert_code(self, msg):
        return covert_to_unicode(msg)
    
    def __create_new_node(self, node_name, node_text = None):
        '''为xml文件添加一个结点,其中node_text可以为空'''        
        if self.__dom == None:
            raise (Exception, '创建结点时，document对象还不存在')
        # 创建的是结点只有结点名
        if None == node_text:
            return self.__dom.createElement(self._covert_code(node_name))
        else:
            newNode = self.__dom.createElement(self._covert_code(node_name))
            newText = self.__dom.createTextNode(self._covert_code(node_text))
            newNode.appendChild(newText)
            return newNode
            
    def begin_cov(self):
        '''begin_cov(self) --> None 创建coverage.xml文档和根结点'''
        try:
            impl = minidom.getDOMImplementation()
            self.__dom = impl.createDocument(None, 'coverages', None)
            self.__root = self.__dom.documentElement
        except:
            traceback.print_exc()
            raise (Exce3ption, '创建coverage xml根结点失败')
        
    def add_cov(self, type, name, total_line, effective_line, covered_line, cover_rate):
        if self.__root == None:
            raise (Exception, '创建结点时，root结点不存在对象不存不存在')
        
        type_node = self.__create_new_node("Type", type)
        name_node = self.__create_new_node("Name", name)
        total_line_node = self.__create_new_node("TotalLine", total_line)
        effective_line_node = self.__create_new_node("EffectiveLine", effective_line)
        covered_line_node = self.__create_new_node("CoveredLine", covered_line)
        cover_line_node = self.__create_new_node("CoverRate", cover_rate)
        new_coverage_node = self.__create_new_node("coverage")
        
        new_coverage_node.appendChild(type_node)
        new_coverage_node.appendChild(name_node)
        new_coverage_node.appendChild(total_line_node)
        new_coverage_node.appendChild(effective_line_node)
        new_coverage_node.appendChild(covered_line_node)
        new_coverage_node.appendChild(cover_line_node)
        self.__root.appendChild(new_coverage_node)
    
    def end_cov(self):
        try:
            f = open(self.__cov_path, 'wb')
            writer = codecs.lookup('utf-8')[3](f)
            self.__dom.writexml(writer, encoding='utf-8')  
            writer.close()
            f.close()
            return True
        except (Exception, err):
            traceback.print_exc() 
            raise (Exception, '写coverage.xml文件出错')
            
if __name__ == '__main__':
    test = CreateCovXml('cov.xml')
    test.begin_cov()
    test.add_cov(
            type = 'total',
            name = '',
            total_line = '58455',                    
            effective_line = '16623',
            covered_line = '11368',
            cover_rate = '68.38717'
        )
    test.add_cov(
            type = 'total',
            name = r'/哈哈/哈哈',
            total_line = '123',                    
            effective_line = '28',
            covered_line = '16',
            cover_rate = '57.14286'
        )  
    test.end_cov()
##    print 'endl'
